package com.flightgame.controllers;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.flightgame.hibernate.OwnershipDao;
import com.flightgame.hibernate.UserDao;
import com.flightgame.services.FlightServices;
import com.flightgame.services.JSONServices;
import com.flightgame.services.MessageServices;
import com.flightgame.tools.Utils;

@Controller
@RequestMapping("/flight")
public class FlightController {
	@Autowired
	private JSONServices jsonServices;
	@Autowired
	private FlightServices flightServices;
	@Autowired
	private MessageServices messageServices;
	@Autowired
	private Utils utils;
	@Autowired
	private OwnershipDao ownershipDao;
	@Autowired
	private UserDao userDao;
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public void createFlight(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String username = request.getParameter("username");
		String itemname = request.getParameter("itemname");
		Writer writer = response.getWriter();
		
		int ownershipId_aircraft = Integer.parseInt(request.getParameter("id"));
		
		int success = flightServices.createFlight(username, itemname, ownershipId_aircraft);
		if(success == utils.SUCCESS) writer.write(jsonServices.getSuccess(true, "",null).toString());
		else writer.write(jsonServices.getSuccess(false,utils.getMessage(success),null).toString());
		response.setCharacterEncoding("UTF-8");
	}
	
	@RequestMapping(value = "/refresh", method = RequestMethod.POST)
	public void refreshPosition(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{
		int ownershipId_aircraft = Integer.parseInt(request.getParameter("id"));
		double newLat = Double.parseDouble(request.getParameter("lat"));
		double newLon = Double.parseDouble(request.getParameter("lon"));
		double newAlt = Double.parseDouble(request.getParameter("alt"));
		String radarRange = request.getParameter("radar");
		Writer writer = response.getWriter();
		Utils utils = new Utils();
		List <String> ranges = utils.tokenizeCommaString(radarRange);
		
		JSONObject flightData = jsonServices.getFlightsOnBoundedCoordinates(ranges.get(0),ranges.get(1),ranges.get(2),ranges.get(3));
		flightData.put("fuel",flightServices.getFuelOfAircraft(ownershipId_aircraft));
		flightData.put("airports",jsonServices.getAirportsOnBoundedCoordinates(ranges.get(0),ranges.get(1),ranges.get(2),ranges.get(3)).get("airports"));
		
		flightData.put("messages",jsonServices.getUserMessages(ownershipDao.getOwnership(ownershipId_aircraft).getUsername()).get("messages"));
		
		
		flightServices.refreshFlightPosition(ownershipId_aircraft, newLat, newLon, newAlt);
		writer.write(flightData.toString());
		response.setCharacterEncoding("UTF-8");
	}
	
	@RequestMapping(value = "/end", method = RequestMethod.POST)
	public void endFlight(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{
		Writer writer = response.getWriter();
		int ownershipId_aircraft = Integer.parseInt(request.getParameter("id"));
		String user = ownershipDao.getOwnership(ownershipId_aircraft).getUsername();
		String airportCode = request.getParameter("airportcode");
		
		int success = flightServices.endFlight(ownershipId_aircraft, airportCode);
		
		if(success == utils.SUCCESS) writer.write(jsonServices.getSuccess(true, "",jsonServices.getUserOwnerships(user)).toString());
		else writer.write(jsonServices.getSuccess(false,utils.getMessage(success),null).toString());
		response.setCharacterEncoding("UTF-8");
	}

	@RequestMapping(value = "/buyfuel", method = RequestMethod.POST)
	public void buyFuelToAircraft(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{
		int ownershipId_aircraft = Integer.parseInt(request.getParameter("id")); 
		int ownershipId_gasStation = Integer.parseInt(request.getParameter("idstation"));
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		int success = flightServices.buyFuelToAircraft(ownershipId_aircraft, ownershipId_gasStation, quantity);
		Writer writer = response.getWriter();
		
		JSONObject flightData = new JSONObject();
		
		flightData.put("fuel",flightServices.getFuelOfAircraft(ownershipId_aircraft));
		flightData.put("credits",userDao.getUser(ownershipDao.getOwnership(ownershipId_aircraft).getUsername()).getCredits());
		
		if(success == utils.SUCCESS) writer.write(jsonServices.getSuccess(true,"",flightData).toString());
		else writer.write(jsonServices.getSuccess(false,utils.getMessage(success),null).toString());
	}
	
	
	@RequestMapping(value = "/newmessage", method = RequestMethod.POST)
	public void sendMessage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String sendId = request.getParameter("sendid");
		String receiveId = request.getParameter("receiveid");
		String isFlightMessage = request.getParameter("isflightmsg");
		String message = request.getParameter("message");
		Writer writer = response.getWriter();
		
		int success = messageServices.createNewMessage(sendId, receiveId, isFlightMessage, message);
		
		if(success == utils.SUCCESS) writer.write(jsonServices.getSuccess(true, "",null).toString());
		else writer.write(jsonServices.getSuccess(false,utils.getMessage(success),null).toString());
	}
	
}
